import { Pie } from '@antv/g2plot'
import { useEffect, useState } from 'react'

import { getRemFontSize } from '../Line'

const data = [
  { type: '分类一', value: 27 },
  { type: '分类二', value: 25 },
  { type: '分类三', value: 18 },
  { type: '分类四', value: 15 },
  { type: '分类五', value: 10 },
  { type: '其他', value: 5 }
]

const PieChart = () => {
  const [chart, setChart] = useState<null | Pie>()

  useEffect(() => {
    const piePlot = new Pie('pieChart', {
      appendPadding: 10,
      data,
      angleField: 'value',
      colorField: 'type',
      radius: 1,
      innerRadius: 0.64,
      meta: {
        value: {
          formatter: (v) => `¥ ${v}`
        }
      },
      legend: {
        itemName: {
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        }
      },
      label: {
        type: 'inner',
        offset: '-50%',
        autoRotate: false,
        style: { textAlign: 'center' },
        formatter: ({ percent }) => `${(percent * 100).toFixed(0)}%`
      },
      statistic: {
        title: {
          offsetY: -8,
          style: {
            fontSize: '2rem'
          }
        },
        content: {
          offsetY: -4,
          style: {
            fontSize: '4rem'
          }
        }
      },
      // 添加 中心统计文本 交互
      interactions: [
        { type: 'element-selected' },
        { type: 'element-active' },
        {
          type: 'pie-statistic-active',
          cfg: {
            start: [
              { trigger: 'element:mouseenter', action: 'pie-statistic:change' },
              {
                trigger: 'legend-item:mouseenter',
                action: 'pie-statistic:change'
              }
            ],
            end: [
              { trigger: 'element:mouseleave', action: 'pie-statistic:reset' },
              {
                trigger: 'legend-item:mouseleave',
                action: 'pie-statistic:reset'
              }
            ]
          }
        }
      ]
    })

    piePlot.render()
    setChart(piePlot)
  }, [])

  useEffect(() => {
    window.addEventListener('resize', resize)
    resize() // 初始化
    return () => {
      window.removeEventListener('resize', resize)
    }
  }, [chart])

  const resize = () => {
    if (!chart) return
    chart.update({
      label: {
        style: {
          fontSize: getRemFontSize() * 1.85
        }
      },
      legend: {
        itemName: {
          style: {
            fontSize: getRemFontSize() * 1.25
          }
        }
      }
    })
  }

  return <div id={'pieChart'} style={{ height: '100vh', width: '100vw' }}></div>
}

export default PieChart
